const { join, extname } = require('path');
const { promisify } = require('util');
const { readFile } = require('fs');
const read = promisify(readFile)
const { createServer } = require('http');

const Config = require('./config.js');
const Watch = require('./watch.js');
const Socket = require('./socket.js');

const heads = {
	'html': 'text/html;charset=utf-8',
	'js': 'application/javascript;charset=utf-8',
	'json': 'application/json;charset=utf-8',
	'css': 'text/css;charset=utf-8',
	'gif': 'image/gif',
	'jpeg': 'image/jpeg',
	'jpg': 'image/jpeg',
	'png': 'image/png',
	'svg': 'image/svg+xml;charset=utf-8',
}

const main = async () => {
	const config = new Config();
	const socket = await new Socket().listen(10086)
	new Watch(config)
		.start()
		.onchange(() => socket.sendReload());

	const server = createServer(async (request, response) => {
		try {
			let filename = request.url
			if (request.url === '/') {
				filename = './index.html'
			}
			const suffix = extname(filename).replace('.', '')
			response.writeHead(200, { 'Content-Type': heads[suffix] || 'text/plain' })
			const file = await read(join(config.getValue('start-path'), filename))
			response.write(file)
			response.end()
		} catch (err) {
			response.writeHead(404, { 'Content-Type': 'text/plain' })
			response.end("The accessed resource does not exist!")
		}
	})

	const port = config.getValue('port')
	server.listen({
		host: '127.0.0.1',
		port: port,
		exclusive: true
	}, async () => {
		console.log('start server success!')
		console.log('host:', `http://127.0.0.1:${port}`)
		open(`http://127.0.0.1:${port}`)
	})
};

const { exec } = require('child_process')
const open = (url) => {
	switch (process.platform) {
		case "darwin":
			exec(`open ${url}`)
			return
		case "win32":
			exec(`start ${url}`)
			return
		default:
			exec(`xdg-open ${url}`)
			return
	}
}


main();
